from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import View
from .models import AddProject, Category,ProjectList,Opinion,WorkLoad,ReportList,Postion
from contract.models import ContractList
from users.models import UserWork,UserProfile
from pure_pagination import Paginator, EmptyPage, PageNotAnInteger
from django.http import HttpResponse
import os,re
from django.db.models import Q
from datetime import datetime

class ProjectListView(View):
    '''项目列表：立项-->实施清单-->合同等'''
    def get(self, request):
        '''获取所有立项项目'''
        all_project = AddProject.objects.all().order_by('addtime')
        # # 热门课程推荐
        # hot_courses = Course.objects.all().order_by('-click_nums')[:3]
        # # 搜索功能
        search_keywords = request.GET.get('q', '')
        if search_keywords:
            # 在name字段进行操作,做like语句的操作。i代表不区分大小写
            # or操作使用Q
            all_project = all_project.filter(Q(name__icontains=search_keywords) | Q(company__fullname__icontains=search_keywords))
        # 排序
        # sort = request.GET.get('sort', "")
        # if sort:
        #     if sort == "students":
        #         all_courses = all_courses.order_by("-students")
        #     elif sort == "hot":
        #         all_courses = all_courses.order_by("-click_nums")
        # 分页
        try:
            page = request.GET.get('page', 1)
        except PageNotAnInteger:
            page = 1
        p = Paginator(all_project,2 , request=request)
        projects = p.page(page)
        return render(request, "layui/index.html", {
            "all_project":projects.object_list,
            # 'sort': sort,
        })

#显示所有大事记
def timeline(request):
    showlist = UserWork.objects.all().order_by('-add_time')
    userlist = UserProfile.objects.all()
    search_keywords = request.GET.get('q', '')
    if search_keywords:
        showlist=showlist.filter(Q(user__nick_name__icontains=search_keywords))
    # 分页
    try:
        page = request.GET.get('page', 1)
    except PageNotAnInteger:
        page = 1
    p = Paginator(showlist,30 , request=request)
    showlist_page = p.page(page)
    return render(request, "layui/timeline.html", {
        'showlist':showlist,
        'showlist_page':showlist_page,
        'userlist':userlist,
        'search_keywords':search_keywords,
    })
#按项目查看大事记
def timeline_byproject(request):
    getaddprojects= AddProject.objects.all().order_by('-addtime')
    # 分页
    try:
        page = request.GET.get('page', 1)
    except PageNotAnInteger:
        page = 1
    p = Paginator(getaddprojects,30 , request=request)
    project_page = p.page(page)
    return render(request, "layui/timeline_byproject.html", {
        'getaddprojects':getaddprojects,
        'project_page':project_page,
    })
#添加大事记
def addtimeline(request):
    pass

#显示project统计页面和清单
def index(request):
    #数量统计
    add_project = AddProject.objects.all().order_by('-addtime')
    add_project_count = add_project.count()
    project_count = ProjectList.objects.all().count()
    category = Category.objects.all()
    opinions = Opinion.objects.all()
    reports = ReportList.objects.all()
    contracts =ContractList.objects.all()
    userWorks = UserWork.objects.all()
    search_word = request.GET.get('w', '')
    if search_word:
        add_project=add_project.filter(category__name__icontains=search_word)
# #当前日期格式
# cur_date = datetime.datetime.now().date()
# #前一天日期
# yester_day = cur_date - datetime.timedelta(days=1)
# #前一周日期
# week = cur_date - datetime.timedelta(weeks=1)
# #查询前一周数据,也可以用range,我用的是glt,lte大于等于
# obj_list=Customer.objects.filter(deal_date__gte=week, deal_date__lte=cur_date)
    try:
        page = request.GET.get('page', 1)
    except PageNotAnInteger:
        page = 1
    p = Paginator(add_project,10 , request=request)
    projects = p.page(page)
    return render(request, "layui/geo_projects.html",{
        'add_project_count':add_project_count,
        'project_count':project_count,
        'all_project':projects,
        'opinions':opinions,
        'contracts':contracts,
        'userWorks':userWorks,
        'category':category,
        'search_word':search_word,
        })
def show_projects(request):

    return render(request, "layui/show_projects.html",{
        'projects':projects,
        })
def show_detail(request,peoject_id):

    return render(request, "layui/show_detail.html",{
        'projects':projects,
        })
def map_show(request):

    return render(request, "mapjs/index.html")
    
def get_uploadpage(request):

    return  render(request, "upload_page.html")
#实现文件上传功能
def attachment_upload(request):
    att_file = request.FILES.get('attachment', None)
    doc_uuid = request.POST.get('doc_uuid', None)

    if att_file:
        # 保存文件到硬盘中
        file_dir = os.path.join(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'project'), att_file.name)
        f = open(file_dir, 'wb')
        for i in att_file.chunks():
            f.write(i)
        f.close()
        # 下载和预览的url
        url = settings.MEDIA_URL + att_file.name
        file_type = re.search(r'[^.]+\w$', att_file.name).group()   # 提取文件后缀名

        # 文件类型，可自行增删
        img_list = ['jpg', 'jpeg', 'jpe', 'gif', 'png', 'pns', 'bmp', 'png', 'tif']
        pdf_list = ['pdf','doc','docx','xls']
        text_list = ['txt', 'md', 'csv', 'nfo', 'ini', 'json', 'php', 'js', 'css']

        # bootstrap fileinput 上传文件的回显参数，initialPreview（列表），initialPreviewConfig（列表）
        initialPreview = []
        # 根据上传的文件类型，生成不同的HTML，
        if file_type in img_list:
            initialPreview.append("<img src='" + url + "' class='file-preview-image' style='max-width:100%;max-height:100%;'>")
        elif file_type in pdf_list:
            initialPreview.append("<div class='file-preview-frame'><div class='kv-file-content'><embed class='kv-preview-data file-preview-pdf' src='" + url +
                                  "' type='application/pdf' style='width:100%;height:160px;'></div></div>")
        elif file_type in text_list:
            initialPreview.append("<div class='file-preview-frame'><div class='kv-file-content'><textarea class='kv-preview-data file-preview-text' title='" + att_file.name +
                                  "' readonly style='width:213px;height:160px;'></textarea></div></div>")
        else:
            initialPreview.append("<div class='file-preview-other'><span class='file-other-icon'><i class='glyphicon glyphicon-file'></i></span></div>")

        initialPreviewConfig = [{
            'caption': att_file.name,   # 文件标题
            'type': file_type,  # 文件类型
            'downloadUrl': url, # 下载地址
            'url': '/del_doc_file/',    # 预览中的删除按钮的url
            'size': os.path.getsize(file_dir),  # 文件大小
            'extra': {'doc_uuid': doc_uuid},    # 删除文件携带的参数
            'key': att_file.name,   # 删除时ajax携带的参数
        }]
        # 返回json数据，initialPreview initialPreviewConfig 会替换初始化插件时的这两个参数 append:True 将内容添加到初始化预览
        return HttpResponse(json.dumps({'initialPreview':initialPreview, 'initialPreviewConfig':initialPreviewConfig,'append': True}))
    else:
        return HttpResponse(json.dumps({'status': False}))
